console.log("init background.js");

// background.js
chrome.runtime.onInstalled.addListener(() => {
  console.log("Extension installed or updated.");
});

// 监听标签页更新事件
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab: any) => {
  if (
    changeInfo.status === "complete" &&
    tab.url.startsWith("http://localhost/")
  ) {
    // 当前标签页的 URL 匹配 http://localhost/
    console.log("Current tab matches http://localhost/:", tab.url);

    // 你可以在这里执行你需要的操作
    // 例如，向页面注入脚本或发送消息给内容脚本
  }
});

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  console.log("message", message);
  console.log("sender", sender);
  sendResponse("成功接收了!!!");
});

function wx_request(url: string, callback: Function) {
  const xhr = new XMLHttpRequest();
  xhr.open("GET", url);
  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {
      callback(xhr.responseText);
    }
  };
  xhr.send();
}

chrome.webRequest.onBeforeRequest.addListener(
  function (detail) {
    console.log("detail.url - ", detail.url);
  },
  { urls: ["<all_urls>"] },
  ["blocking"]
);

chrome.webRequest.onResponseStarted.addListener(
  function (detail) {
    console.log("detail - ", detail);
  },
  { urls: ["<all_urls>"] },
  ["responseHeaders"]
);

chrome.browserAction.onClicked.addListener(function () {
  console.log("hello bg - ");
});

// background.js

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.action === "buttonClicked") {
    console.log("Received message from content script: Button was clicked!");
    // 你可以在这里执行其他操作
    sendResponse({ message: "Button click received by background script" });
  }
  return true; // 表示异步响应
});
